package com.zxcl.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zxcl.constant.WxConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

@Configuration
@EnableConfigurationProperties(WxOfficialProperties.class)
@Slf4j
public class WxOfficialAutoConfiguration {

    @Autowired
    private WxOfficialProperties wxOfficialProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostConstruct
    public void init() {
        refreshWxToken();
    }

    @Scheduled(initialDelay = 7100 * 1000, fixedRate = 7100 * 1000)
    public void refreshWxToken() {
        String realTokenUrl = String.format(wxOfficialProperties.getTokenUrl(), wxOfficialProperties.getAppId(), wxOfficialProperties.getAppSecret());
        String wxTokenStr = new RestTemplate().getForObject(realTokenUrl, String.class);
        JSONObject jsonObject = JSON.parseObject(wxTokenStr);
        String accessToken = jsonObject.getString("access_token");
        if (!StringUtils.hasText(accessToken)) {
            log.error("微信公众平台token获取失败{}", wxTokenStr);
            return;
        }
        // 存到redis
        redisTemplate.opsForValue().set(WxConstant.WX_OFFICIAL_TOKEN_KEY, accessToken);
    }
}
